package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.Item;
import csu.web.mypetstore.domain.Product;
import csu.web.mypetstore.service.CatalogService;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SearchServlet extends HttpServlet {

    private static final String VIEW_PRODUCT = "/WEB-INF/jsp/search/search.jsp";

    private String searchName;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        int count = 0;
        searchName = req.getParameter("keyword");
        List<String> productNameList = new ArrayList<>(Arrays.asList("Bulldog",
                "Chihuahua",
                "Dalmation",
                "Poodle",
                "Golden Retriever",
                "Labrador Retriever",
                "Koi",
                "Goldfish",
                "Angelfish",
                "Tiger Shark",
                "Persian",
                "Manx",
                "Iguana",
                "Rattlesnake",
                "Amazon Parrot",
                "Finch"));
        if(productNameList.contains(searchName)){
            count = 1;
        }

        if (count == 1) {
            CatalogService catalogService = new CatalogService();
            Product searchProduct = catalogService.getProductByName(searchName);
            List<Item> searchProductList = catalogService.getItemListBySearchName(searchName, searchProduct);

            HttpSession httpSession = req.getSession();
            httpSession.setAttribute("searchProduct", searchProduct);
            httpSession.setAttribute("searchProductList", searchProductList);
            req.getRequestDispatcher(VIEW_PRODUCT).forward(req, resp);
        }else{
            String msg="The product you entered does not exist, please enter it again!";

            resp.getWriter().write("<script language=javascript>alert('" +msg+ "');window.location='mainFrom'</script>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
